const audioContext = new AudioContext();

console.log("sampleRate:"+audioContext.sampleRate)
var scriptProcessor = audioContext.createScriptProcessor(4096,0,1)
scriptProcessor.onaudioprocess = audioCallback
scriptProcessor.connect(audioContext.destination);

// get the audio element
const audioElement = document.querySelector('audio');

const gainNode = audioContext.createGain();

const pannerOptions = { pan: 0 };
const panner = new StereoPannerNode(audioContext, pannerOptions);


// select our play button
const playButton = document.querySelector('button');

playButton.addEventListener('click', function() {

    // check if context is in suspended state (autoplay policy)
    if (audioContext.state === 'suspended') {
        audioContext.resume();
    }

    // play or pause track depending on state
    if (this.dataset.playing === 'false') {
        audioElement.play();
        this.dataset.playing = 'true';
    } else if (this.dataset.playing === 'true') {
        audioElement.pause();
        this.dataset.playing = 'false';
    }

}, false);

audioElement.addEventListener('ended', () => {
    playButton.dataset.playing = 'false';
}, false);

const volumeControl = document.querySelector('#volume');

volumeControl.addEventListener('input', function() {
    gainNode.gain.value = this.value;
}, false);

const pannerControl = document.querySelector('#panner');

pannerControl.addEventListener('input', function() {
    panner.pan.value = this.value;
}, false);

function audioCallback(event){
    var outputBuffer = event.outputBuffer
    var outputBufferLength = outputBuffer.length
    var channelData = outputBuffer.getChannelData(0)
    for(var i = 0; i < outputBufferLength; i++){
		channelData[i] = Math.random() * 2 - 1
	}
    console.log('audioCallback')
    var frameStartTime = new Date()
    console.log('time:'+frameStartTime)
}
